package com.woniuxy.woniuhis.aspect;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.woniuhis.annotation.SystemLog;
import com.woniuxy.woniuhis.entity.Log;
import com.woniuxy.woniuhis.service.LogService;

/**
 * 
 * 	记录系统日志的切面类 
 * 
 * 	aop + 自定义注解 实现记录系统日志
 *
 */
@Component
@Aspect
public class LogAspect {

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private LogService logService;

	/**
	 * 一般方法的记录日志
	 * 
	 * @param joinPoint
	 */
	@Before("@annotation(com.woniuxy.woniuhis.annotation.SystemLog)")
	public void log(JoinPoint joinPoint) {
		this.saveLog(joinPoint, getMethodDescription(joinPoint));
	}

	/**
	 * 登录记录日志，登录成功才需要记录日志，所以使用后置返回通知
	 * 
	 * @param joinPoint
	 */
	@AfterReturning(value = "execution(* com.woniuxy.woniuhis.controller.UserController.userLogin(..))")
	public void loginLog(JoinPoint joinPoint) {
		this.saveLog(joinPoint, "用户登录日志记录");
	}
	
	/**
	 * 系统日志保存
	 * @param joinPoint
	 * @param description
	 */
	private void saveLog(JoinPoint joinPoint, String description) {
		Log log = new Log();

		// 获取用户名
		String username = "admin";
		// 获取请求的属性
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		// request 对象
		HttpServletRequest request = requestAttributes.getRequest();
		List<Object> params = Arrays.asList(joinPoint.getArgs());
		System.out.println("方法的参数: "+params.toString());
		// 进行脱敏处理
//		List<String> result = SensitiveUtil.desJsonCollection(params);
		try {
			log.setUsername(username);
			log.setOperation(description);
			log.setMethod(joinPoint.getSignature().getName());
			log.setIp(request.getRemoteAddr());
			log.setCreateTime(new Date());

			log.setParams(objectMapper.writeValueAsString(params));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			log.setParams(null);
		}
		// 将日志信息添加到数据库中
		logService.insert(log);
	}
	
	/**
	 * 获取自定义注解的值，描述方法操作的值
	 * @param joinPoint
	 * @return
	 */
	public String getMethodDescription(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		String value = signature.getMethod().getAnnotation(SystemLog.class).value();
		return value;
	}
}
